<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Support\BaiduPush\PushSdk;

use Log;

class BaiduPushOrderEndedMsg implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $order;

    /**
     * Create a new job instance.
     *
     * @param $order
     */
    public function __construct($order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $sdk = new PushSdk();

        // 消息内容.
        $message = array (
            'title' => '加电侠',
            // 消息内容
            'description' => "充电结束，" . $this->order->service_end_at->format('m月d日h时i分'),
            'open_type' => 2,
            'pkg_content' => '#Intent;component=com.loxin.charger/.ChargefullActivity;end',
            'custom_content' => [
                'order_sn' => $this->order->order_sn,
                'device_sn' => $this->order->device_sn,
                'duration' => $this->order->consume_duration,
                'real_pay_money' => $this->order->real_pay_money,
                'pay_score' => 0,
                'balance' => $this->order->user->balance,
                'start_time' => $this->order->service_start_at->format('m月d日h时i分'),
                'end_time' => $this->order->service_end_at->format('m月d日h时i分'),
            ]
        );

        if ($this->order->real_pay_money == 0) {
            foreach ($this->order->payments as $payment) {
                if ($payment->pay_mode == 'score') {
                    $message['custom_content']['pay_score'] += $payment->money;
                }
            }
        }

        // 设置消息类型为 通知类型.
        $opts = array (
            'msg_type' => 1,
            'msg_topic' => 'order-ended'
        );

        if (!empty($this->order->user->baidu_push_channel_id) && in_array($this->order->source, ['ios', 'android']) && $this->order->status == 'success') {
            // channel_id
            $channel_id = $this->order->user->baidu_push_channel_id;

            // 指定消息推送
            $rs =  $sdk->pushMsgToSingleDevice($channel_id, $message, $opts);

            Log::debug('百度消息推送', [$channel_id, $message, $opts, $rs, $sdk->getLastErrorCode(), $sdk->getLastErrorMsg()]);
        }
    }
}
